//Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var UserPrefs=function() {
    this.units=readCookie('option_units','M');
};

UserPrefs.prototype.setUnits=function (u){
   this.units=u;
   createCookie('option_units', this.units,7);
};

UserPrefs.prototype.toDist=function(x,dec){
  if (x==null) return 0;
  if (dec==null) dec=2;
  if (this.units=="M") return (x/1000.0).toFixed(dec);
  return (x*0.0006214).toFixed(dec);
};

UserPrefs.prototype.toEle=function(x){
  if (x==null) return 0;
  if (this.units=="M") return x.toFixed(0);
  return (x*3.2808).toFixed(0) ;
};

UserPrefs.prototype.distLabel=function(){
  if (this.units=="M") return " km";
  return " mi";
};

UserPrefs.prototype.eleLabel=function(){
  if (this.units=="M") return " m";
  return " f";
};

var prefs=new UserPrefs();


function T4BLog(s){
  //$('debug_log').innerHTML=$('debug_log').innerHTML+"<br/>"+s;
  console.log(s);
}

function doLogin(){
  Dialog.confirm({url: "/account/login_dialog", options: {method: 'get'}},  {
    okLabel: "login",  cancelLabel: "cancel",
    width:400,  className:"alphacube",
     onShow: function(){$('loginField').focus();},
     onOk: function(win){
      var myAjax = new Ajax.Request( '/account/login', {
        method: 'post', parameters: Form.serialize('loginForm')
    })
    }
  });
};

function doPrefs(){
  Dialog.confirm({url: "/account/show_prefs", options: {method: 'get'}},  {
    width:400,  className:"alphacube",
     onOk: function(win){
       prefs.setUnits($('option_units').value);
       if (typeof t4b !='undefined') t4b.setUnits();
       Dialog.closeInfo();
    }
  });
};

function addTag(){
  new_tag=$('new_tag').value
  if (new_tag.length==0) return;
  if (new_tag.indexOf(' ')>=0) {
    alert("no spaces allowed in tag!\n\nTips: use 'MountVentoux' or 'mount_ventoux' instead of 'mount ventoux'");
    return;
  }
  $('tags').options[$('tags').options.length]=new Option(new_tag);
  $('new_tag').value="";
  resetTags();
}

function deleteTag(){
  var s=$('tags').selectedIndex;
  if (s>=0) $('tags').options[s]=null;
  resetTags();
}

function resetTags(){
  var s=[];
  for (var i=0;i<$('tags').options.length;i++)
    s.push($('tags').options[i].value);
  $('track_tag_list').value=s.join(' ');
}

//--cookies

function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
};

function readCookie(name,defValue) {
        if(!document.cookie) return defValue;
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return defValue;
};

function eraseCookie(name) {
        createCookie(name,"",-1);
};

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
};

function showTab(id){
  var t=$$(".divTabs");
  for (var i=0;i<t.length;i++)
    if (t[i].id!=id) Element.hide(t[i]);
  Element.show(id);
}

function _(key){
  if (typeof(I18n[_lang][key])!='undefined') return I18n[_lang][key];
  return key;
};

function _set_lang(lang){
  if (typeof(I18n[lang]) == 'undefined') {
    alert('unsupported language');
    return;
  }
  _lang=lang;
  createCookie('lang',lang);
  alert(_('set_this_language'));
};

var TableBuilder = Class.create({
  initialize: function(attrs){
    this.html="<table ";
    if (attrs) this.html+=attrs;
    this.html+=">";    this.close=false;
    this.closeRow=true;
  },
  startRow:function(attr){
    if (attr==null) attr="";
    if (!this.closeRow) this.endRow();
    this.html+="<tr "+attr+">";
  },
  endRow:function(){
    this.html+="</tr>";
    this.closeRow=true;
  },
  td: function (s){
    this.tag("td",s);
  },
  tdr: function (s){
    this.tag("td",s,"style='text-align:right'");
  },
  th: function (s){
    this.tag("th",s);
  },
  th: function (s,style){
    this.tag("th",s,"style='"+style+"'");
  },
  setHeaderBeforeTable:function(s){
    this.html="<h3>"+s+"</h3>"+this.html;
  },
  tag:function (tagname,tagvalue,attrs){
    this.html+="<"+tagname;
    if (attrs) this.html+=" "+attrs;
    this.html+=">"+tagvalue+"</"+tagname+">";
  },
  toDiv:function(divName){
    if (!this.closeRow) this.endRow();
    if (!this.close){
      this.html+="</table>";
      this.close=true;
    }
    if ($(divName)){
      Element.show($(divName));
      Element.update($(divName),this.html);
    }
  }
});


var I18n = {
 en:{
'max_route_length_exceeded':'Max route length exceeded',
'type_address':'Type address',
'not_found':'Not found',
'distance_to_last':'Distance to last',
'cannot_link':'Cannot link!',
'link_this':'Link this',
'empty_route':'Empty route',
'ascent':'Ascent',
'cannot_undo':'Cannot undo',
'cannot_redo':'Cannor redo',
'loading_track...':'Loading track...',
'track_not_found':'Track not found',
'directions':'Directions',
'ok':'OK',
'delete':'Delete',
'set_this_language':'Set english language',
'update_profile_first':'Please, update profile first',
'max_climb_length':'Climb length excedeed',
'climb_diff_under_thr':'Climb difference under threshold',
'climb_slope_under_thr':'Climb slope under threshold',
'zoom_too_high':'Zoom level too high',
'Climb_from':'From',
//profile climbs
"from":"from",
"to":"to",
"distance":"distance",
"elev":"elev",
"difference":"difference",
"avg slope":"avg slope",
"max slope":"max slope",
"label":"label",
"Max ascent speed":"Max ascent speed",
"slope_for":"for"
 },
 it:{
'max_route_length_exceeded':'Max lunghezza traccia superata',
'type_address':'Inserisci indirizzo',
'not_found':'Non trovato',
'distance_to_last':'Distanza da ultimo',
'cannot_link':'Non posso collegare!',
'link_this':'Collega questo',
'empty_route':'Percorso vuoto',
'ascent':'Ascesa',
'cannot_undo':'Impossibile annullare',
'cannot_redo':'Impossibile ripetere',
'loading_track...':'Caricamento traccia...',
'track_not_found':'Traccia non trovata',
'directions':'Indicazioni',
'ok':'OK',
'delete':'Elimina',
'set_this_language':'Impostata lingua italiana',
'update_profile_first':'Devi prima aggiornare il profilo',
'max_climb_length':'Lunghezza massima salita superata',
'climb_diff_under_thr':'Dislivello sotto limite minimo',
'climb_slope_under_thr':'Pendenza sotto limite minimo',
'zoom_too_high':'Livello zoom troppo elevato',
'Climb_from':'Versante',
"from":"Da",
"to":"a",
"distance":"distanza",
"elev":"Elev",
"difference":"Dislivello",
"avg slope":"Pendenza media",
"max slope":"Pendenza max",
"label":"label",
"Max ascent speed":"Max VAM",
"slope_for":"su"
 },
 es:{
'max_route_length_exceeded': 'Se excediÃ³ la longitud mÃ¡xima de ruta',
'type_address':'Introduzca direcciÃ³n',
'not_found':'No encontrado',
'distance_to_last':'Distancia a el anterior',
'cannot_link':'No puedo enlazar !',
'link_this':'Enlazar esto',
'empty_route':'Ruta vacÃ­a',
'ascent':'Ascendente',
'cannot_undo':'No se puede deshacer',
'cannot_redo':'No se puede rehacer',
'loading_track...':'Cargando track...',
'track_not_found':'Track no encontrada',
'directions':'Direcciones',
'ok':'OK',
'delete':'Borrar',
'set_this_language':'Set spanish language',
'update_profile_first':'Please, update profile first',
'max_climb_length':'Climb length excedeed',
'climb_diff_under_thr':'Climb difference under threshold',
'climb_slope_under_thr':'Climb slope under threshold',
'zoom_too_high':'Zoom level too high',
'Climb_from':'From',
"from":"from",
"to":"to",
"distance":"distance",
"elev":"elev",
"difference":"difference",
"avg slope":"avg slope",
"max slope":"max slope",
"label":"label",
"Max ascent speed":"Max ascent speed",
"slope_for":"for"

},
'pt-BR':{
'max_route_length_exceeded': 'Comprimento máximo de rota ultrapassado',
'type_address':'Introduza endereço',
'not_found':'Não encontrado',
'distance_to_last':'Distância ao anterior',
'cannot_link':'Não é possível ligar',
'link_this':'ligar isto',
'empty_route':'Rota vazía',
'ascent':'Ascensão',
'cannot_undo':'Não é possível desfazer',
'cannot_redo':'Não é possível refazer',
'loading_track...':'Carregando trajeto...',
'track_not_found':'Trajeto não encontrado',
'directions':'Indicações',
'ok':'OK',
'delete':'Apagar',
'set_this_language':'Establecido Portoguese',
'update_profile_first':'Please, update profile first',
'max_climb_length':'Climb length excedeed',
'climb_diff_under_thr':'Climb difference under threshold',
'climb_slope_under_thr':'Climb slope under threshold',
'zoom_too_high':'Zoom level too high',
'Climb_from':'From',
"from":"from",
"to":"to",
"distance":"distance",
"elev":"elev",
"difference":"difference",
"avg slope":"avg slope",
"max slope":"max slope",
"label":"label",
"Max ascent speed":"Max ascent speed",
"slope_for":"for"

}
};

var _lang=readCookie('lang','en');
